package com.crane.common.core.dto;

import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.ErrorCode;

import java.text.MessageFormat;

/**
 * @author zhenxing.pi
 */
@SuppressWarnings("rawtypes")
public class SingleResponse<T> extends Response {

    private static final long serialVersionUID = -9056348611555749608L;

    private T data;

    public static <T> SingleResponse<T> of(T data) {
        SingleResponse<T> singleResponse = new SingleResponse<>();
        /**
         * 兼容以前格式
         */
        singleResponse.setCode(BasicErrorCode.SERVER_SUCCESS.getErrCode());
        singleResponse.setSuccess(true);
        singleResponse.setData(data);
        return singleResponse;
    }

    public static SingleResponse buildFailure(String errMessage) {
        SingleResponse response = new SingleResponse();
        response.setSuccess(false);
        response.setCode(BasicErrorCode.SYS_ERROR.getErrCode());
        response.setErrMsg(errMessage);
        return response;
    }

    public static SingleResponse buildFailure(String errCode, String errMessage) {
        SingleResponse response = new SingleResponse();
        response.setSuccess(false);
        response.setCode(errCode);
        response.setErrMsg(errMessage);
        return response;
    }


    public static SingleResponse buildFailure(ErrorCode errorCode) {
        SingleResponse response = new SingleResponse();
        response.setSuccess(false);
        response.setCode(errorCode.getErrCode());
        response.setErrMsg(errorCode.getErrDesc());
        return response;
    }

    public static SingleResponse buildFailure(ErrorCode errorCode, Object... replacements) {
        SingleResponse response = new SingleResponse();
        response.setSuccess(false);
        response.setCode(errorCode.getErrCode());
        response.setErrMsg(MessageFormat.format(errorCode.getErrDesc(), replacements));
        return response;
    }


    public static SingleResponse buildSuccess() {
        SingleResponse response = new SingleResponse();
        /**
         * 兼容以前格式
         */
        response.setCode(BasicErrorCode.SERVER_SUCCESS.getErrCode());
        response.setSuccess(true);
        return response;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

}
